"use strict";

/**
 * 
 * @param {Array|Rule}
 *            promotionalRules
 */
function Checkout(promotionalRules) {
	this.items = {};
	this.rules = promotionalRules || [];
};

/**
 * 
 * @param {Item}
 *            item
 * @returns {Object}
 */
Checkout.prototype.get = function(item) {
	return this.items[item.getProductCode()];
};

Checkout.prototype.getItems = function() {
	return this.items;
};

/**
 * 
 * @param {Item}
 *            item
 */
Checkout.prototype.scan = function(item) {

	var itemCode = item.getProductCode();

	if (this.items[itemCode] == undefined) {
		this.items[itemCode] = {
			"item" : item,
			"quantity" : 1
		};
	} else {
		++this.items[itemCode].quantity;
	}
};

/**
 * 
 * @param {Item}
 *            item
 * @param {int}
 *            quantity
 */
Checkout.prototype.remove = function(item, quantity) {
	var localItem = this.items[item.getProductCode()];

	if (localItem == undefined) {
		return;
	} else {
		var itemQuantity = localItem.quantity;
		quantity = quantity || itemQuantity;
		if (quantity > itemQuantity) {
			localItem.quantity = 0;
		} else {
			localItem.quantity -= quantity;
		}
	}
};

Checkout.prototype.subTotal = function() {
	var total = 0;

	for ( var i in this.items) {
		total += this.items[i].item.getPrice() * this.items[i].quantity;
	}

	return total;
};

Checkout.prototype.total = function() {
	var total = this.subTotal();

	if (this.rules.length > 0) {

		for ( var i = 0; i < this.rules.length; ++i) {
			total = this.rules[i].applyRule(this.items, total);
		}
	}

	return Math.round(total * Math.pow(10, 2)) / Math.pow(10, 2);
};
